package com.example.watchcat2k.finalproject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class User_Info_Activity extends AppCompatActivity {
    //个人信息控件
    ImageView back;
    CircleImageView icon;
    TextView username;
    TextView name;
    TextView descr;
    Button follow;
    Button has_follow;
    TextView look_blogs;
    Boolean first_click = true;

    ListView listView;

    User_basic_info user_info;
    String username1 = "";

    MylistAdapter mylistAdapter;




    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_user_card);


        init();

        // //判断是否已关注,初始化关注按钮
        require_follow();



        //点击事件
        setclick();

    }

    void init(){
        back = findViewById(R.id.imageView_user_card_back);
        icon = findViewById(R.id.circleImageView_user_card_image);
        username = findViewById(R.id.textView_user_card_username);
        name = findViewById(R.id.textView_user_card_name);
        descr = findViewById(R.id.textView_user_card_descr);
        follow = findViewById(R.id.button_user_card_follow);
        has_follow = findViewById(R.id.button_user_card_has_follow);
        look_blogs = findViewById(R.id.listview_user_card_click);

        listView = findViewById(R.id.listview_user_card_blog);

        //获取点击的人的基本信息以及访问人信息
        Intent intent = getIntent();
        user_info = (User_basic_info) intent.getSerializableExtra("user");
        username1 = intent.getStringExtra("username1");

        //初始化个人信息
        username.setText(user_info.getUsername());
        name.setText(user_info.getName()+"（昵称）");
        descr.setText(user_info.getDescription());
        byte[] bytes = Base64.decode(user_info.getIcon(), Base64.DEFAULT);
        Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        icon.setImageBitmap(bm);

        mylistAdapter = new MylistAdapter(this);


    }

    void setclick(){
        //返回按钮
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //点击关注
        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //网络请求
                try {
                    OkHttpClient build = new OkHttpClient.Builder()
                            .connectTimeout(2, TimeUnit.SECONDS)
                            .readTimeout(2, TimeUnit.SECONDS)
                            .writeTimeout(2, TimeUnit.SECONDS)
                            .build();

                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("http://129.204.116.253:8080")

                            .addConverterFactory(GsonConverterFactory.create())

                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                            // build 即为okhttp声明的变量，下文会讲
                            .client(build)

                            .build();

                    AddorDeleteFollow data = new AddorDeleteFollow(username1, "add", user_info.getName());
                    AddOrDeleteFollowService service = retrofit.create(AddOrDeleteFollowService.class);
                    service.postFollow(data)
                            .subscribeOn(Schedulers.io())//请求在新的线程中执行
                            .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                            .subscribe(new DisposableObserver<Send_Blog_Confirm_Packet>() {
                                @Override
                                public void onNext(Send_Blog_Confirm_Packet data) {
                                    if(data.isStatus()){
                                        Toast.makeText(User_Info_Activity.this, "成功关注", Toast.LENGTH_SHORT).show();
                                        follow.setVisibility(View.INVISIBLE);
                                        has_follow.setVisibility(View.VISIBLE);
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    Toast.makeText(User_Info_Activity.this, "关注失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                                    Log.i("test", "onError: "+e.toString());
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }catch (Exception o){
                    Toast.makeText(User_Info_Activity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
                    Log.i("test", "onError: "+o.toString());
                }
            }
        });


        //取消关注
        has_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //网络请求
                try {
                    OkHttpClient build = new OkHttpClient.Builder()
                            .connectTimeout(2, TimeUnit.SECONDS)
                            .readTimeout(2, TimeUnit.SECONDS)
                            .writeTimeout(2, TimeUnit.SECONDS)
                            .build();

                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("http://129.204.116.253:8080")

                            .addConverterFactory(GsonConverterFactory.create())

                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                            // build 即为okhttp声明的变量，下文会讲
                            .client(build)

                            .build();

                    AddorDeleteFollow data = new AddorDeleteFollow(username1, "delete", user_info.getName());
                    AddOrDeleteFollowService service = retrofit.create(AddOrDeleteFollowService.class);
                    service.postFollow(data)
                            .subscribeOn(Schedulers.io())//请求在新的线程中执行
                            .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                            .subscribe(new DisposableObserver<Send_Blog_Confirm_Packet>() {
                                @Override
                                public void onNext(Send_Blog_Confirm_Packet data) {
                                    if(data.isStatus()){
                                        Toast.makeText(User_Info_Activity.this, "已取消关注", Toast.LENGTH_SHORT).show();
                                        follow.setVisibility(View.VISIBLE);
                                        has_follow.setVisibility(View.INVISIBLE);
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    Toast.makeText(User_Info_Activity.this, "取消关注失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                                    Log.i("test", "onError: "+e.toString());
                                }

                                @Override
                                public void onComplete() {

                                }
                            });
                }catch (Exception o){
                    Toast.makeText(User_Info_Activity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
                    Log.i("test", "onError: "+o.toString());
                }
            }
        });

        //点击查询
        look_blogs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(first_click){
                    first_click = false;
                    look_blogs.setText("正在加载中...");
                    //获取用户所有的博客
                    get_user_all_blogs();
                }
            }
        });
    }


    //判断是否已关注
    void require_follow(){
        //网络请求
        try {
            OkHttpClient build = new OkHttpClient.Builder()
                    .connectTimeout(2, TimeUnit.SECONDS)
                    .readTimeout(2, TimeUnit.SECONDS)
                    .writeTimeout(2, TimeUnit.SECONDS)
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://129.204.116.253:8080")

                    .addConverterFactory(GsonConverterFactory.create())

                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                    // build 即为okhttp声明的变量，下文会讲
                    .client(build)

                    .build();

            user1_follow_user2_packet data = new user1_follow_user2_packet(username1, user_info.getName());
            WhetherFollowService service = retrofit.create(WhetherFollowService.class);
            service.postFollow(data)
                    .subscribeOn(Schedulers.io())//请求在新的线程中执行
                    .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                    .subscribe(new DisposableObserver<Follow>() {
                        @Override
                        public void onNext(Follow data) {
                            if(data.getFollow()){ //已关注
                                Toast.makeText(User_Info_Activity.this, "已关注该用户"+user_info.getName(), Toast.LENGTH_SHORT).show();
                                has_follow.setVisibility(View.VISIBLE);
                                follow.setVisibility(View.INVISIBLE);
                            }
                            else { //未关注
                                Toast.makeText(User_Info_Activity.this, "未关注该用户"+user_info.getName(), Toast.LENGTH_SHORT).show();
                                has_follow.setVisibility(View.INVISIBLE);
                                follow.setVisibility(View.VISIBLE);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(User_Info_Activity.this, "获取是否关注失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                            Log.i("test", "onError: "+e.toString());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }catch (Exception o){
            Toast.makeText(User_Info_Activity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
            Log.i("test", "onError: "+o.toString());
        }
    }


    //获取用户的所有博客
    void get_user_all_blogs(){
        //网络请求
        try {
            OkHttpClient build = new OkHttpClient.Builder()
                    .connectTimeout(2, TimeUnit.SECONDS)
                    .readTimeout(2, TimeUnit.SECONDS)
                    .writeTimeout(2, TimeUnit.SECONDS)
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://129.204.116.253:8080")

                    .addConverterFactory(GsonConverterFactory.create())

                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                    // build 即为okhttp声明的变量，下文会讲
                    .client(build)

                    .build();

            final only_username data_ = new only_username(user_info.getUsername());
            UserBlogService service = retrofit.create(UserBlogService.class);
            service.postgetBlogs(data_)
                    .subscribeOn(Schedulers.io())//请求在新的线程中执行
                    .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                    .subscribe(new DisposableObserver<User_All_Blogs>() {
                        @Override
                        public void onNext(User_All_Blogs data) {

                            if(data != null){
                                mylistAdapter.all_datas = data.getBlogs();
                                listView.setAdapter(mylistAdapter);
                                look_blogs.setText("已经到底啦");
                                Toast.makeText(User_Info_Activity.this, "博客总数：" + data.getBlogs().size(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            Toast.makeText(User_Info_Activity.this, "查询博客失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                            Log.i("test", "onError: "+e.toString());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }catch (Exception o){
            Toast.makeText(User_Info_Activity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
            Log.i("test", "onError: "+o.toString());
        }
    }



    //自定义适配器
    public class MylistAdapter extends BaseAdapter{
        ArrayList<User_All_Blogs.blog>all_datas;
        Context context;
        TextView content;
        TextView date;
        ImageView image1;
        ImageView image2;
        ImageView image3;
        ImageView image4;
        ImageView image5;
        ImageView image6;

        public MylistAdapter(Context context_){
            all_datas = new ArrayList<>();
            this.context = context_;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public int getCount() {
            return all_datas.size();
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_user_blog, null);
            }

            //绑定
            content = convertView.findViewById(R.id.item_user_blog_content);
            date = convertView.findViewById(R.id.item_user_blog_date);
            image1 = convertView.findViewById(R.id.item_user_blog_image1);
            image2 = convertView.findViewById(R.id.item_user_blog_image2);
            image3 = convertView.findViewById(R.id.item_user_blog_image3);
            image4 = convertView.findViewById(R.id.item_user_blog_image4);
            image5 = convertView.findViewById(R.id.item_user_blog_image5);
            image6 = convertView.findViewById(R.id.item_user_blog_image6);

            //填充数据
            content.setText(all_datas.get(position).getContent());
            date.setText(all_datas.get(position).getDate());
            int photos_num = all_datas.get(position).getPhotos().size();
            if(photos_num == 0){//无照片
                image1.setVisibility(View.GONE);
                image2.setVisibility(View.GONE);
                image3.setVisibility(View.GONE);
                image4.setVisibility(View.GONE);
                image5.setVisibility(View.GONE);
                image6.setVisibility(View.GONE);
            }else if(photos_num == 1){//一张照片
                image1.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(0)));
                image2.setVisibility(View.INVISIBLE);
                image3.setVisibility(View.INVISIBLE);
                image4.setVisibility(View.GONE);
                image5.setVisibility(View.GONE);
                image6.setVisibility(View.GONE);
            }else if(photos_num == 2){
                image1.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(0)));
                image2.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(1)));
                image3.setVisibility(View.INVISIBLE);
                image4.setVisibility(View.GONE);
                image5.setVisibility(View.GONE);
                image6.setVisibility(View.GONE);
            }else if(photos_num == 3){
                image1.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(0)));
                image2.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(1)));
                image3.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(2)));
                image4.setVisibility(View.GONE);
                image5.setVisibility(View.GONE);
                image6.setVisibility(View.GONE);
            }else if(photos_num == 4){
                image1.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(0)));
                image2.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(1)));
                image3.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(2)));
                image4.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(3)));
                image5.setVisibility(View.INVISIBLE);
                image6.setVisibility(View.INVISIBLE);
            }else if(photos_num == 5){
                image1.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(0)));
                image2.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(1)));
                image3.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(2)));
                image4.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(3)));
                image5.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(4)));
                image6.setVisibility(View.INVISIBLE);
            }else {
                image1.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(0)));
                image2.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(1)));
                image3.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(2)));
                image4.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(3)));
                image5.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(4)));
                image6.setImageBitmap(getBitmap(all_datas.get(position).getPhotos().get(5)));
            }

            return convertView;
        }

        public Bitmap getBitmap(String icon){
            byte[] bytes = Base64.decode(icon, Base64.DEFAULT);
            Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bm;
        }
    }


    //几个网络接口
    public interface WhetherFollowService{
        @POST("/follow/isFollow")
        Observable<Follow> postFollow(@Body user1_follow_user2_packet user1_follow_user2_packet_);
    }


    public interface UserBlogService{
        @POST("/blog/getUserBlog")
        Observable<User_All_Blogs> postgetBlogs(@Body only_username only_username_);
    }


    public interface AddOrDeleteFollowService{
        @POST("/follow/addOrDeleteFollow") //Send_Blog_Confirm_Packet这里是共用的
        Observable<Send_Blog_Confirm_Packet> postFollow(@Body AddorDeleteFollow data);
    }

    public class Follow implements Serializable {
        private Boolean isFollow;

        public void setFollow(Boolean follow) {
            isFollow = follow;
        }

        public Boolean getFollow() {
            return isFollow;
        }
    }

    public class User_All_Blogs implements Serializable{
        private ArrayList<blog> blogs;

        public void setBlogs(ArrayList<blog> blogs) {
            this.blogs = blogs;
        }

        public ArrayList<blog> getBlogs() {
            return blogs;
        }


        public class blog{
            private String author;
            private String icon;
            private String content;
            private String date;
            private int lookNumber;
            private int likeNumber;
            private int commentNumber;
            private ArrayList<String>photos;

            public void setIcon(String icon) {
                this.icon = icon;
            }

            public void setPhotos(ArrayList<String> photos) {
                this.photos = photos;
            }

            public void setContent(String content) {
                this.content = content;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public void setAuthor(String author) {
                this.author = author;
            }

            public void setCommentNumber(int commentNumber) {
                this.commentNumber = commentNumber;
            }

            public void setLikeNumber(int likeNumber) {
                this.likeNumber = likeNumber;
            }

            public void setLookNumber(int lookNumber) {
                this.lookNumber = lookNumber;
            }

            public String getIcon() {
                return icon;
            }

            public ArrayList<String> getPhotos() {
                return photos;
            }

            public String getContent() {
                return content;
            }

            public String getDate() {
                return date;
            }

            public int getCommentNumber() {
                return commentNumber;
            }

            public int getLikeNumber() {
                return likeNumber;
            }

            public int getLookNumber() {
                return lookNumber;
            }

            public String getAuthor() {
                return author;
            }
        }
    }

    public class AddorDeleteFollow{
        private String username;
        private String name;
        private String type;

        public AddorDeleteFollow(String username, String type, String name){
            this.username = username;
            this.name = name;
            this.type = type;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getUsername() {
            return username;
        }

        public String getName() {
            return name;
        }

        public String getType() {
            return type;
        }
    }




}